package com.assets.Fragment;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import android.os.HandlerThread;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.assets.Check.newTanWanCheck.New_Check_choose;
import com.assets.Check.offlineCheck.OfflineCheckActivity;
import com.assets.Check.offlineCheck.OfflineCheckData;
import com.assets.Login.login;
import com.assets.MainActivity;
import com.assets.bean.InventoryDataBean;
import com.assets.newNHF.UhfApplication;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.dao.CheckDao;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Asset;
import com.assets.room.entity.Check;
import com.assets.room.entity.CheckData;
import com.assets.room.entity.Dept;
import com.assets.room.entity.Place;
import com.assets.room.entity.Receives;
import com.assets.room.entity.ReceivesDetail;
import com.assets.room.entity.ReceivesReapply;
import com.assets.room.entity.Type;
import com.assets.room.entity.User;
import com.assets.util.MyOkHttp;
import com.assets.util.NetworkUtil;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.demo.WaveSwipeRefreshLayout;
import com.assets.Adapter.Check_adapter;
import com.assets.Check.Check_choose;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.bean.fragmentfor_bean;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jjh.CheckBean;
import com.jjh.TAssetAsset;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018/12/25.
 * 盘点
 */
public class Fragment4 extends Fragment {
    private static final String TAG = "jiangjianhua";

    private float versionCode = 0;
    private ImageView imageView, screen;
    private ListView listView;
    private SlideSideMenuExampleActivity mainActivity;
    private WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    private String downloadDataUrl = "http://" + Url.IP + "/api/getAllAssetData";

    private String sendDataUrl = "http://" + Url.IP + "/api/sendAllAssetData";
    private String url = "http://" + Url.IP + "/api/checkQuery";
    private List<Map<String, Object>> list = new ArrayList<>();
    private List<Map<String, Object>> newList = new ArrayList<>();

    private List<Map<String, Object>> underway = new ArrayList<>();//待盘点
    private List<Map<String, Object>> Have_inventory = new ArrayList<>();//已盘点
    private List<Map<String, Object>> For_inventory = new ArrayList<>();//待盘点
    private HandlerThread handlerThread;

    private Gson gson = new Gson();

    private SlideSideMenuExampleActivity activity;
    private Handler handler;

    private MyDataBase db;
    private Button getAllTaskBtn;
    private ProgressBar downloadBar;
    private Dialog dialog;
    private Button butAllTaskBtn;
    private List<Type> typeList;
    private List<Place> placeList;
    private List<CheckData> checkDataList;
    private List<Check> checkList;
    private List<User> userList;
    private List<Dept> deptList;
    private List<Asset> assetList;
    private List<Receives> receivesList;
    private List<ReceivesDetail> receivesDetailList;
    private List<ReceivesReapply> receivesReapplyList;
    private Check_adapter re_ad;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity = (SlideSideMenuExampleActivity) getActivity();
        View view = inflater.inflate(R.layout.fragment_second4, null);
        getAllTaskBtn = view.findViewById(R.id.btn_get_task);
        butAllTaskBtn = view.findViewById(R.id.btn_put_task);
        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mainActivity = (SlideSideMenuExampleActivity) getActivity();
        listView = (ListView) getActivity().findViewById(R.id.checklist);

        init();

        handlerThread = new HandlerThread("word");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper());
        listView.setOnItemClickListener((parent, view, i, id) -> {

            String myId = newList.get(i).get("odd").toString();
            String myState = newList.get(i).get("odd").toString();
            String myCreateDate = newList.get(i).get("Date_created").toString();
            String myCheckNum = newList.get(i).get("sum").toString();
            String myCreateUser = newList.get(i).get("creator") == null ? "" : newList.get(i).get("creator").toString();
            Intent intent = new Intent(mainActivity, com.assets.Check.Check.class);
            intent.putExtra("id", myId);
            intent.putExtra("state", myState);
            intent.putExtra("createDate", myCreateDate);
            intent.putExtra("checkNum", myCheckNum);
            intent.putExtra("createUser", myCreateUser);
            startActivity(intent);
        });

    }


    /**
     * 用来初始化数据/下拉刷新数据
     */
    private void load() {
//        mainActivity.showDialog("加载数据ing...");

        Log.d("xxxxxxx", "懂了");
        newList.clear();


        Map<String, String> map = new HashMap<>();
        map.put("userId", Since_case.getInstance().getUserId());
        MyOkHttp.getInstance().post(Url.checkQuery(), map, new MyOkHttp.requestMessage() {

            @Override
            public void requestFail() {
                mainActivity.showToast("连接服务器失败");
                mainActivity.canDialog();
            }

            @Override
            public void requestComplete() {

            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String result = response.body().string();
                Log.d("xxxxxxx", "result: " + result);
//                List<CheckBean> o = gson.fromJson(result, new TypeToken<CheckBean>() {
//                }.getType());
                CheckBean[] checks = gson.fromJson(result, CheckBean[].class);
                List<CheckBean> checksList = Arrays.asList(checks);
                for (CheckBean check : checksList) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("odd", check.getCheckId());//盘点单号
                    map.put("creator", check.getName()); //创建人
                    map.put("Date_created", check.getCreatedate());
                    map.put("sum", check.getNum());
                    map.put("scope", "4");
                    map.put("state", check.getStatus());
                    newList.add(map);
                }
                Log.d("xxxxxxx", "newList: " + newList);
                activity.runOnUiThread(() -> {
                    re_ad = new Check_adapter(activity, newList);
                    listView.setAdapter(re_ad);
                    mWaveSwipeRefreshLayout.setRefreshing(false);
//                    activity.canDialog();
                });
                Log.d("xxxxxxx", "result: " + gson.toJson(checks));
            }
        });

    }

    private void getAPKVersion() {

        NetworkUtil.getVersion(Url.myHttp())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
                        try {
                            String versionNo = responseBody.string();
                            Log.d("点击更新", "onNext: " + versionNo);
                            if (TextUtils.isEmpty(versionNo)) {
//                               showToast("version文件异常");
                                Toast.makeText(getActivity(), "version文件有误", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            float updateVersion = Float.parseFloat(versionNo.substring(versionNo.indexOf(":") + 1));
                            if (updateVersion - versionCode <= 0) {
                                Toast.makeText(getActivity(), "当前是最新版", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            getActivity().runOnUiThread(() -> {
                                android.app.AlertDialog builder = new AlertDialog.Builder(getActivity())
                                        .setTitle("更新提示")
                                        .setMessage("有新版本是否更新！")
                                        .setNegativeButton("否", (dialog, which) -> {

                                        }).setPositiveButton("是", (dialog, which) -> {
                                            updateApp();
                                        }).create();
                                builder.setCanceledOnTouchOutside(false);
                                builder.show();
                            });
                        } catch (IOException e) {

                            throw new RuntimeException(e);
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        Log.d("点击更新", "e: " + e.getMessage() + ", " + Url.myHttp());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @SuppressLint("CheckResult")
    private void updateApp() {

        NetworkUtil.updateApp(Url.myHttp())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .map(new Function<ResponseBody, File>() {
                    @SuppressLint("CheckResult")
                    @Override
                    public File apply(ResponseBody responseBody) throws Throwable {
                        File flie = getActivity().getExternalFilesDir("apkData");
                        File apk = new File(flie, "pda.apk");
                        InputStream inputStream = responseBody.byteStream();
                        FileOutputStream outputStream = new FileOutputStream(apk);
                        byte[] bytes = new byte[4096];
                        int len;
                        while ((len = inputStream.read(bytes)) != -1) {
                            outputStream.write(bytes, 0, len);
                        }
                        inputStream.close();
                        outputStream.close();
                        return apk;
                    }
                }).subscribe(file -> {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        // 判断当前应用是否有安装未知应用权限
                        if (!getActivity().getPackageManager().canRequestPackageInstalls()) {
                            // 如果没有权限，跳转到设置页面请求权限
                            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getActivity().getPackageName()));
                            startActivity(intent);
                        } else {
                            // 如果已经有权限，执行安装操作
                            installUnknownAppRx(file);
                        }
                    } else {
                        // 如果不是 Android O 及以上版本，直接执行安装操作
                        installUnknownAppRx(file);
                    }
                }, error -> {

                });


    }

    private void installUnknownAppRx(File file) {


        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri data;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
            // 通过FileProvider创建一个content类型的Uri
            data = FileProvider.getUriForFile(getContext(), "ABC.provider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
        } else {
            data = Uri.fromFile(file);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        startActivity(intent);

    }

    private void getVersion() {
        // 获取当前版本号信息
        PackageInfo packInfo = null;
        try {
            packInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        assert packInfo != null;
        versionCode = packInfo.versionCode;
    }


    private void init() {

        screen = (ImageView) mainActivity.findViewById(R.id.screen);
        screen.setImageResource(R.mipmap.up_file);
//        screen.setVisibility(View.GONE);
        TextView title = mainActivity.findViewById(R.id.title_text);

        title.setText("盘点");
        screen.setOnClickListener(v -> {
            getVersion();
            getAPKVersion();
        });
//        screen.setOnClickListener(v -> new AlertView("筛选", null, "取消", new String[]{"全部"}, new String[]{"已盘点", "待盘点", "进行中"}, mainActivity, AlertView.Style.ActionSheet, new OnItemClickListener() {
//            @Override
//            public void onItemClick(Object o, int position) {
//                if (position == 0) {
//                    //适配器，刚刚重写的！
//                    re_ad = new Check_adapter(mainActivity, newList);
//                    listView.setAdapter(re_ad);
//                }
//                if (position == 1) {
//                    Have_inventory.clear();
//                    for (int i = 0; i < newList.size(); i++) {
//                        if (newList.get(i).get("state").equals("已盘点")) {
//                            Map<String, Object> map = new HashMap<String, Object>();
//                            map.put("odd", newList.get(i).get("odd"));
//                            map.put("Date_created", newList.get(i).get("Date_created"));
//                            map.put("creator", newList.get(i).get("creator"));
//                            map.put("sum", newList.get(i).get("sum"));
//                            map.put("Inventory_date", newList.get(i).get("Inventory_date"));
//                            map.put("scope", newList.get(i).get("scope"));
//                            map.put("state", newList.get(i).get("state"));
//                            Have_inventory.add(map);
//                        }
//                    }
//                     re_ad = new Check_adapter(mainActivity, Have_inventory);
//                    listView.setAdapter(re_ad);
//                }
//                if (position == 2) {
//                    For_inventory.clear();
//                    for (int i = 0; i < list.size(); i++) {
//                        if (newList.get(i).get("state").equals("待盘点")) {
//                            Map<String, Object> map = new HashMap<String, Object>();
//                            map.put("odd", newList.get(i).get("odd"));
//                            map.put("Date_created", newList.get(i).get("Date_created"));
//                            map.put("creator", newList.get(i).get("creator"));
//                            map.put("sum", newList.get(i).get("sum"));
//                            map.put("Inventory_date", newList.get(i).get("Inventory_date"));
//                            map.put("scope", newList.get(i).get("scope"));
//                            map.put("state", newList.get(i).get("state"));
//                            For_inventory.add(map);
//                        }
//                    }
//                    re_ad = new Check_adapter(mainActivity, For_inventory);
//                    listView.setAdapter(re_ad);
//                }
//                if (position == 3) {
//                    underway.clear();
//                    for (int i = 0; i < newList.size(); i++) {
//                        if (newList.get(i).get("state").equals("进行中")) {
//                            Map<String, Object> map = new HashMap<String, Object>();
//                            map.put("odd", newList.get(i).get("odd"));
//                            map.put("Date_created", newList.get(i).get("Date_created"));
//                            map.put("creator", newList.get(i).get("creator"));
//                            map.put("sum", newList.get(i).get("sum"));
//                            map.put("Inventory_date", newList.get(i).get("Inventory_date"));
//                            map.put("scope", newList.get(i).get("scope"));
//                            map.put("state", newList.get(i).get("state"));
//                            underway.add(map);
//                        }
//                    }
//                    underway.toString();
//                     re_ad = new Check_adapter(mainActivity, underway);
//                    listView.setAdapter(re_ad);
//                }
//            }
//        }).show());
        imageView = (ImageView) getActivity().findViewById(R.id.opmenu);
        imageView.setOnClickListener((View.OnClickListener) v -> {
            SlideSideMenuTransitionLayout mSlideSideMenu = (SlideSideMenuTransitionLayout) getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();
        });

        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) getActivity().findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(() -> {
            //模拟3秒的加载过程
            //接下来可以刷新ListView
            new Handler().postDelayed(this::load, 1200);
        });

    }

    private void checkDetailQuery(String checkId) {
        Map<String, String> map = new HashMap<>();
        map.put("checkId", checkId);
        mainActivity.post("http://192.168.1.139:8586/api/checkQuery", map, responseData -> {
            LogUtils.d(responseData);
            OfflineCheckData offlineCheckData = MyOkHttp.getInstance().getGson().fromJson(responseData, OfflineCheckData.class);
            Intent intent = new Intent(getContext(), OfflineCheckActivity.class);
            intent.putExtra("offlineCheckData", offlineCheckData);
            startActivity(intent);
        });
    }


    @Override
    public void onStart() {
        if (handler != null) {
            handler.postDelayed(this::load, 500);
        }
        LogUtils.d("onStart");
        super.onStart();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        handlerThread.quit();

    }


}
